package com.htu.courseService.common.exception;

/**
 * Created By JNNarrator on 2024/9/6 18:03
 * email: jiangn09@chinatelecom.cn
 */

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.htu.courseService.common.enums.ResponseCodeEnum;
import com.htu.courseService.common.vo.R;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
@Slf4j
public class BaseExceptionHandler {
	
	/**
	 * 处理BaseException
	 *
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BaseException.class)
	public R<?> handlerGlobalException(HttpServletResponse response, BaseException e) {
//		response.setStatus(e.getResponseCode().getCode());
		return R.fail(e.getResponseCode().getCode(), e.getResponseCode().getMessage());
	}
	
	@ExceptionHandler(BindException.class)
	public R<?> handlerBindException(HttpServletResponse response, BindException e) {
		log.error("请求异常：", e);
		BindingResult bindingResult = e.getBindingResult();
		FieldError fieldError = bindingResult.getFieldError();
		assert fieldError != null;
		String defaultMessage = fieldError.getDefaultMessage();
		return R.fail(ResponseCodeEnum.BAD_REQUEST.getCode(), defaultMessage);
		
	}
	
	/**
	 * 处理Exception
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public R<?> handlerException(Exception e) {
		log.error("请求异常：", e);
		return R.fail(-1,"系统异常");
	}
	@ExceptionHandler(NotLoginException.class)
	public R<?> handlerException(NotLoginException e) {
		return R.fail(401,e.getMessage());
	}
	@ExceptionHandler(NotPermissionException.class)
	public R<?> handlerException(NotPermissionException e) {
		return R.fail(401,e.getMessage());
	}
	@ExceptionHandler(BusinessException.class)
	public R<?> handlerException(BusinessException e){
		return R.fail(e.getErrorCodeEnum());
	}
}
